const https = require('https');
const http = require('http');
const fs = require('fs');
const path = require('path');
const { URL } = require('url');

function downloadImage(imageUrl, savePath) {
  // 解码真实图片地址（从URL参数中提取mediaurl）
  const urlParams = new URL(imageUrl).searchParams;
  const realImageUrl = urlParams.get('mediaurl') || imageUrl;

  // 解析真实图片地址的协议
  const parsedUrl = new URL(realImageUrl);
  const protocolModule = parsedUrl.protocol === 'https:' ? https : http;

  // 生成文件名和路径
  const filename = path.basename(parsedUrl.pathname) || 'image.jpg';
  const fullPath = path.join(savePath, filename);

  // 创建保存目录
  if (!fs.existsSync(savePath)) {
    fs.mkdirSync(savePath, { recursive: true });
  }

  // 配置请求选项
  const options = {
    hostname: parsedUrl.hostname,
    path: parsedUrl.pathname + parsedUrl.search,
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
  };

  // 发送请求
  const req = protocolModule.get(options, (res) => {
    // 处理重定向
    if ([301, 302, 303].includes(res.statusCode) && res.headers.location) {
      downloadImage(res.headers.location, savePath);
      return;
    }

    // 校验状态码
    if (res.statusCode !== 200) {
      console.error(`HTTP错误码: ${res.statusCode}`);
      return;
    }

    // 创建写入流
    const fileStream = fs.createWriteStream(fullPath);
    res.pipe(fileStream);

    // 完成回调
    fileStream.on('finish', () => {
      fileStream.close();
      console.log(`✅ 图片已保存至: ${fullPath}`);
    });
  });

  // 错误处理
  req.on('error', (err) => {
    console.error(`❌ 下载失败: ${err.message}`);
  });
}

// 使用示例
const imageUrl = 'https://www.bing.com/images/search?view=detailV2&ccid=utaYcpUG&id=A3DE25E7962FF052D3967F837BAA9A25877E1B48&thid=OIP.utaYcpUG2h4jMdYBtSn8TAHaE8&mediaurl=https%3A%2F%2Fpicb3.photophoto.cn%2F15%2F828%2F15828023_1.jpg&cdnurl=https%3A%2F%2Fth.bing.com%2Fth%2Fid%2FR.bad698729506da1e2331d601b529fc4c%3Frik%3DSBt%252bhyWaqnuDfw%26pid%3DImgRaw%26r%3D0&exph=801&expw=1200&q=%E5%B1%B1%E6%B0%B4%E9%A3%8E%E6%99%AF%E5%9B%BE%E7%89%87&simid=608046574192325194&form=IRPRST&ck=35727725CE510AF2086D7155F59EB4CC&selectedindex=2&itb=0&cw=1529&ch=847&ajaxhist=0&ajaxserp=0&vt=0&sim=11';
const saveDir = './downloads';
downloadImage(imageUrl, saveDir);